package com.eastfair.questionnaire.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.eastfair.core.utils.StringUtils;
import com.eastfair.enums.SystemSourceEnum;
import com.eastfair.questionnaire.enums.QuestionnaireRelationTypeEnum;
import com.eastfair.questionnaire.service.QuestionnaireRelationService;
import com.eastfair.questionnaire.service.RelationTagService;
import com.eastfair.questionnaire.vo.QuestionnaireRelationVO;
import com.google.common.collect.Lists;
import javafx.util.Pair;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @ClassName RelationTagServiceImpl
 * @Description TODO
 * @Author yuwx
 * @Date 2021/8/30 11:26
 * @Version 1.0
 **/
@Slf4j
@Service
public class RelationTagServiceImpl implements RelationTagService {
    private QuestionnaireRelationService questionnaireRelationService;

    @Autowired
    public RelationTagServiceImpl(QuestionnaireRelationService questionnaireRelationService) {
        this.questionnaireRelationService = questionnaireRelationService;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveTagAnswerRelation(Long projectId, SystemSourceEnum systemSourceEnum, Long answerId, List<Long> tagIdList) {
        if (Objects.isNull(projectId)
                || Objects.isNull(answerId)) {
            throw new NullPointerException("params is null");
        }
        if (CollectionUtil.isEmpty(tagIdList)) {
            questionnaireRelationService.delete(projectId, QuestionnaireRelationTypeEnum.ANSWER_TAG, systemSourceEnum, Lists.newArrayList(answerId));
            return;
        }
        List<Pair<Long, String>> pairList = tagIdList.stream().map(tagId -> new Pair<>(answerId, Objects.isNull(tagId) ? null : String.valueOf(tagId))).collect(Collectors.toList());
        questionnaireRelationService.save(projectId, QuestionnaireRelationTypeEnum.ANSWER_TAG, systemSourceEnum, pairList);
    }

    @Override
    public List<Long> convertAnswerToTag(Long projectId, SystemSourceEnum systemSourceEnum, List<Long> answerIdList) {
        if (Objects.isNull(projectId)) {
            throw new NullPointerException("params is null");
        }
        if (CollectionUtil.isEmpty(answerIdList)) {
            return Collections.emptyList();
        }
        List<QuestionnaireRelationVO> relationList = questionnaireRelationService.listByInternal(projectId, QuestionnaireRelationTypeEnum.ANSWER_TAG, systemSourceEnum, answerIdList);
        return relationList.stream().filter(relation -> !StringUtils.isBlank(relation.getExternalId()))
                .map(relation -> Long.valueOf(relation.getExternalId())).collect(Collectors.toList());
    }

}
